/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.enterprise.web;

import com.assg2.dao.DaoViewer;
import com.movie.Friend;
import com.movie.Viewer;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.Set;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Kevin
 */
public class FriendInfoCommand implements Command {

    public FriendInfoCommand() {
    }

    public String execute(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        //TODO: set the response content type to "text/html" here
        //TODO: You'll have to use getWriter() to output some HTML texts
        //TODO: close the output stream

        response.setContentType("text/html");// from response, set content type
        PrintWriter out = response.getWriter();// from response, get output writer     
        HttpSession session = request.getSession(true);
        int id = Integer.parseInt(request.getParameter("id"));
        DaoViewer dv = new DaoViewer();
        Viewer friend = (Viewer) dv.findById(id);
        Viewer user = (Viewer) session.getAttribute("user");
        user = (Viewer)dv.findById(user.getIdviewer());
        Set friendsSet = user.ListOfFriends();
        if (!friendsSet.isEmpty()) {
            Iterator i = friendsSet.iterator();
            while (i.hasNext()) {
                Viewer f = (Viewer) i.next();
                if (f.getIdviewer() != user.getIdviewer()) {
                    if (f.getIdviewer() == id) {
                        request.setAttribute("isfriend", "true");
                        request.setAttribute("friend", friend);
                        return "/addFriend.jsp";
                    } else {
                        request.setAttribute("isfriend", "false");
                        request.setAttribute("friend", friend);
                        return "/addFriend.jsp";
                    }
                } else {
                    if (f.getIdviewer() == id) {
                        request.setAttribute("isfriend", "true");
                        request.setAttribute("friend", friend);
                        return "/addFriend.jsp";
                    } else {
                        request.setAttribute("isfriend", "false");
                        request.setAttribute("friend", friend);
                        return "/addFriend.jsp";
                    }
                }
            }
        } else if (friendsSet.isEmpty()) {
            request.setAttribute("isfriend", "false");
            request.setAttribute("friend", friend);
            return "/addFriend.jsp";
        }
        return null;


    }
}
